package com.hhj.dao;

import com.hhj.util.JDBCUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class BaseDao {

    /**
     * 万能增删改
     * @param sql sql语句
     * @param arr 参数
     * @return
     */
    public final static int cud(String sql,Object[] arr){
        int updateRows = 0;
        Connection con = null;
        PreparedStatement ps = null;
        try{
            con = JDBCUtil.getConnection();
            ps = con.prepareStatement(sql);
            for(int i = 0; i < arr.length; i++){
                ps.setObject(i+1, arr[i]);
            }
            updateRows = ps.executeUpdate();
        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            close(con,ps,null);
        }
        return updateRows;
    }

    /**
     * 万能查询
     * @param sql
     * @param arr
     * @param con
     * @param ps
     * @return
     */
    public final static ResultSet query(String sql,Object[] arr,Connection con,PreparedStatement ps){
        ResultSet rs = null;
        try {
            ps = con.prepareStatement(sql);
            for (int i = 0; i < arr.length; i++) {
                ps.setObject(i+1,arr[i]);
            }
            rs = ps.executeQuery();
        }catch (SQLException e){
            e.printStackTrace();
        }

        return rs;
    }


    public final static void close(Connection con, PreparedStatement ps, ResultSet rs){

        if(rs != null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(ps != null){
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(con != null){
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();

            }
        }
    }
}
